<template>
	<view class="contain">
		<view class="padding-12">

			<view @click="go('/pages/user/address?type=order')" class="flex bg-color-w b-radius-5">
				<view class="flex flex-1">
					<view class="flex f-a-c f-j-c f-s-0 myicon myicon-address f44-size padding-10 t-color-r"></view>
					<view v-if="address != ''" class="flex f-c flex-1 f-j-c">
						<view class="flex f-a-c">
							<text class="flex f-a-c f-w-b f15-size margin-r12">{{address.realname}}</text>
							<text class="flex f-a-c f12-size t-color-9">{{address.phone}}</text>
						</view>
						<view class="line1 margin-t4 f12-size">{{address.province}}{{address.city}}{{address.area}}{{address.address}}</view>
					</view>
					<view v-if="address == ''" class="flex f-c flex-1 f-j-c">
						<text class="t-color-9">{{i18n['选择收货地址']}}</text>
					</view>
				</view>
				<view class="flex f-s-0 f-a-c f-j-c padding-lr6 van-icon van-icon-arrow t-color-9"></view>
			</view>

			<view v-for="(item,index) in list" class="bg-color-w b-radius-5 padding-12 margin-t12">
				<view class="flex f-a-c margin-b10">
					<text class="flex f-a-c van-icon van-icon-shop-o t-color-y margin-r6"></text>
					<text class="f-w-500 t-color-3">{{item.shopName}}</text>
				</view>
				<view v-for="(goods,idx) in item.goodsList"  :key="idx"  class="flex margin-b10">
					<view class="flex f-s-0 w-70 h-70 b-radius-5 bg-img  margin-r10" :style="goods.goodsSku.img | bgimg(400)+''"></view>
					<view class="flex flex-1 f-c margin-r8">
						<view class="line2 f12-size">{{goods.goods.title}}</view>
						<view class="flex f-a-c margin-t6">
							<view class="flex f-a-c f-j-c padding-lr6 bg-color-f7 f12-size t-color-9 b-radius-2 h-20">{{goods.goodsSku.attrSymbolName}}</view>
						</view>
					</view>
					<view class="flex f-s-0 f-c">
						<view class="text-price f12-size">{{goods.goodsSku.price}}</view>
						<view class="flex f-j-e margin-t6 t-color-9 f11-size">x{{goods.buyNum}}</view>
					</view>
				</view>
				<view class="flex f-a-c f-j-s h-36">
						<text class="f12-size t-color-9 margin-r10">配送方式</text>
						<!-- <text @tap="openShowBox(goods.goods,idx)">{{item.shippingType === 1 ? '快递配送' : '到店核销'}}</text> -->
						<picker @change="bindPickerChange" :value="index" :range="radioList"  :range-key="'title'">
												<text class="">{{shippingTypeTitle}}</text>
						</picker>
				</view>
				<view class="flex f-a-c f-j-s h-36">
					<text class="f12-size t-color-9 margin-r10">{{i18n['快递运费']}}</text>
					<text v-if="item.freightFee <= 0" class=" ">{{i18n['包邮']}}</text>
					<text v-if="item.freightFee > 0" class="text-price">{{item.freightFee | getFinallPrice}}</text>
				</view>
				<!-- <view class="flex f-a-c f-j-s h-36" @tap="showInvoice">
					<text class="f12-size t-color-9 margin-r10">开具发票</text>
					<view class='discount discount_voice' @tap="goInvoice()">
						{{(invoiceData && invoiceData.receiptTitle) ? invoiceData.receiptTitle : '不开发票'}}
						<text class='iconfont icon-jiantou'></text>
					</view>
				</view> -->

				<view @click="getCoupon(index)" class="flex f-a-c f-j-s h-36">
					<text class="f12-size t-color-9 margin-r10">{{i18n['优惠折扣']}}</text>
					<view v-if="item.couponPrice && item.couponPrice != 0" class="flex f-a-c">
						<text class=" t-color-y f12-size">-</text>
						<text class="text-price t-color-y f12-size">{{item.couponPrice}}</text>
						<text class="flex f-a-c van-icon van-icon-arrow t-color-9 "></text>
					</view>
					<view v-else class="flex f-a-c">
						<view class="t-color-9 margin-r6">{{i18n['请选择']}}</view>
						<text class="flex f-a-c van-icon van-icon-arrow t-color-9 "></text>
					</view>
				</view>
				<view class="flex  f-j-s " style="padding-top: 10px;">
					<text class="flex f-s-0  f12-size t-color-9 margin-r10">{{i18n['订单备注']}}</text>
					<view class="flex flex-1">
						<textarea v-model="item.remark" class="f12-size input h-30" value="" placeholder="订单备注可选" />
					</view>
				</view>
				<!-- <view class="flex f-a-c f-j-e">
					<text class="f12-size t-color-9">{{i18n['共1件'] | i18n(2)}}，</text>
					<text class="f12-size ">{{i18n['小计']}}：</text>
					<text class="f12-size text-price t-color-y">2700</text>
				</view> -->
			</view>

		</view>
		<view :style="isIphonex ? 'padding-top:84px;' : 'padding-top:50px;'"></view>
		<view class="flex f-a-c f-j-e h-50 fixed-top bg-color-w padding-lr12 box-c" :style="isIphonex ? 'padding-bottom:34px;' : ''">
			<text class=" t-color-9">{{i18n['共1件'] | i18n(len)}}，</text>
			<text class=" ">{{i18n['小计']}}：</text>
			<text class="text-price t-color-y margin-r12">{{amount | getFinallPrice}}</text>
			<view @click="pay" class="flex f-a-c f-j-c b b-radius-30 w-100 h-36 bg-color-linear-y t-color-w">{{i18n['提交订单']}}</view>
		</view>

		<uni-popup ref="coupon" type="bottom">
			<view class="bg-color-f7 wrap-popup-radius safe-area">
				<view class="flex f-a-c f-j-c padding-12 f16-size">优惠券</view>
				<scroll-view scroll-y="true" style="height:70vh">
					<coupon-item :list="couponList" @choose="chooseCoupon" type="use"></coupon-item>
				</scroll-view>
				<view class="padding-12">
					<view @click="noUseCoupon" class="flex f-a-c f-j-c b-radius-30 h-36 t-color-w bg-color-linear-y">暂不使用</view>
				</view>
			</view>
		</uni-popup>



			<view v-if="isShowBox">
					<checkDelivery :isShowBox="isShowBox" :activeObj="activeObj" @close="boxClose"
						@confirmBtn="getShippingType">
					</checkDelivery>
				</view>
			<addInvoicing ref="addInvoicing" @changeInvoiceClose="changeInvoiceClose" :invoice='invoice'></addInvoicing>
	</view>
</template>
<style scoped>
@import url('../../static/css/iconcolor.css');
.fixed-top {
	top: auto;
	bottom: 0;
}
.input {
	text-align: right;
}
</style>
<script>
	import addInvoicing from '@/components/addInvoicing';
    import checkDelivery from '@/components/checkDelivery/index.vue';
	import couponItem from '@/components/common/couponlist.vue';
	const API = require('@/utils/api/order.js').default;
	const $ = require('@/utils/api.js');
	let self;
	let isflag = true;
	export default {
			components: {
					addInvoicing,
			       couponItem,
					checkDelivery
				},
		filters: {
			time(val) {
				return moment(val * 1000).format('YYYY-MM-DD HH:mm:ss');
			}
		},
		data() {
			return {
				invoice: {
					invoice: false,
					mer_id: 0
				}, //发票组件
				invoiceData: {}, // 发票数据

				invoiceName: '不开发票',
				invoice_func: false,

				addInvoice: {},

				radioList:[
								{
									title:'快递配送',
									shippingType: 1
								},
								{
									title:'到店核销',
									shippingType: 2
								}
							],
					isShowBox: false,
				top: uni.getStorageSync('bartop') ? uni.getStorageSync('bartop') : 0,
				isIphonex: uni.getStorageSync('isIphonex') ? uni.getStorageSync('isIphonex') : false,
				list: [],
				address: '',
				amount: 0,
				len: 0,
				couponList: [],
				commonIndex: '',
				groupId: '',
				joinGroupId: '',
				shippingType:1,
				shippingTypeTitle:"快递运输",
				orderData:{},
			};
		},
		onLoad: function(options) {
			self = this;

			this.orderData = [options];
			this.groupId = options.groupId ? options.groupId : '';
			this.joinGroupId = options.joinId ? options.joinId : '';
			this.init();
			$.setTitle(self.i18n['确认订单']);



			uni.getStorage({
				key: "invoice_Data",
				success: function(res) {
					self.addInvoice = res.data;
					if (res.data) {
						// self.getInvoiceDatas(res.data)
					}
				}
			})

		},
		methods: {
				/**
				 * 开发票
				 */
				goInvoice: function(id) {
					let that = this;
					// that.invoice.invoice = true;
					// that.invoice.mer_id = id;
					that.$refs.addInvoicing.show();
					this.$refs.addInvoicing.getInvoiceDefault();
					this.$refs.addInvoicing.getInvoiceList();
				},
			showInvoice(){
				this.getAgreement();
			},
			/*获取发票说明*/
			getAgreement() {
				let that = this
				that.showProtocol = true;
				that.agrementTtile = '发票说明'
				// getAgreementApi('sys_receipt_agree').then(res => {
					that.protocol = "发票协议 "
				// })
			},
			/*获取发票说明*/
			getCouponAgreement() {
				let that = this
				that.showProtocol = true;
				that.agrementTtile = '优惠券说明'
				getAgreementApi('sys_coupon_agree').then(res => {
					console.log(res);
					that.protocol = res.data.sys_coupon_agree
				})
			},
			// 关闭发票弹窗
			changeInvoiceClose: function(data) {

				this.invoiceData = data
				this.$set(this.invoice, 'invoice', false);
			},

			// getInvoiceData(selectedData) {
			// 	this.invoiceData = {}
			// 	if (selectedData) {
			// 		this.cartInfo.forEach((item, i) => {
			// 			if (item.mer_id == selectedData.mer_id) {
			// 				if (this.cartInfo[i]['invoiceData']) {
			// 					this.cartInfo[i]['invoiceData'] = selectedData
			// 				} else {
			// 					this.$set(this.cartInfo[i], 'invoiceData', selectedData)
			// 				}
			// 			}
			// 			let mer_id = selectedData.mer_id
			// 			this.invoiceData[mer_id] = selectedData;
			// 		});
			// 	} else {
			// 		this.cartInfo.forEach((item, i) => {
			// 			this.$set(this.cartInfo[i], 'invoiceData', {})
			// 		});
			// 	}
			// },
			getInvoiceDatas(selectedData) {
				this.invoiceData = {}
				if (selectedData.length) {
					this.cartInfo.forEach((item, i) => {
						selectedData.forEach((val, j) => {
							if (item.mer_id == val.mer_id) {
								if (this.cartInfo[i]['invoiceData']) {
									this.cartInfo[i]['invoiceData'] = val
								} else {
									this.$set(this.cartInfo[i], 'invoiceData', val)
								}
							}
							let mer_id = val.mer_id
							this.invoiceData[mer_id] = val;
						})
					});
				} else {
					this.cartInfo.forEach((item, i) => {
						this.$set(this.cartInfo[i], 'invoiceData', {})
					});
				}
				console.log(this.invoiceData)
			},



			   bindPickerChange: function(e) {
			            console.log('picker发送选择改变，携带值为', e.detail.value)
			            this.shippingType = (e.detail.value==1)?2:1
						this.shippingTypeTitle = this.radioList[e.detail.value].title
						 console.log('picker发送选择改变，携带值为', this.shippingType)
			        },
					// 打开配送方式弹窗
						openShowBox(item, index) {
							this.activeObj = item
							this.activeIndex = index
							this.isShowBox = true
						},
								boxClose() {
										this.isShowBox = false
									},
			noUseCoupon() {
				let info = self.list[self.commonIndex];
				info['couponPrice'] = 0;
				info['couponId'] = '';
				self.$set(self.list,self.commonIndex,info);
				self.$refs.coupon.close();
				self.getPrice();
			},
			chooseCoupon(data) {
				if(data.reason && data.reason != '') {
					$.$toast(dta.reason);return;
				}
				let info = self.list[self.commonIndex];
				if(data.type == 2) {//折扣券
					let price = 0;
					info.goodsList.forEach((ele,index) => {
						price += ele.goodsSku.price*ele.buyNum;
					})
					info['couponPrice'] = price*(10-data.amount)/10;
				}else{
					info['couponPrice'] = data.discountAmount;
				}
				info['couponId'] = data.id;
				self.$set(self.list,self.commonIndex,info);
				self.$refs.coupon.close();
				self.getPrice();
			},
			getCoupon(parent) {
				const self = this;
				self.commonIndex = parent;
				let info = self.list[parent];
				if(info.couponList){
					self.$refs.coupon.open();
					return;
				}//请求过了无需再次请求
				let idArr = [];
				let cateArr = [];
				let price = 0;
				info.goodsList.forEach((ele,index) => {
					idArr.push(ele.goods.id);
					cateArr.push(ele.goods.cateIds);
					price += ele.goodsSku.price*ele.buyNum;
				})
				$.ajax({
					url: API.canUseCouponListApi,
					data: {
						shopId: info.shopId,
						goodsIds: idArr.join(','),
						cateIds: cateArr.join(','),
						totalAmount: price,
					},
					method: 'GET',
					success(res) {
						self.couponList = res.data ? res.data : [];
						info['couponList'] = self.couponList;
						self.$set(self.list,parent,info);
						self.$refs.coupon.open();
					}
				})
			},
			getPrice() {
				let price = 0;
				let len = 0;
				self.list.forEach((ele,index) => {
					price += ele.freightFee;
					if(ele.couponPrice && ele.couponPrice != 0) {
						price -= ele.couponPrice;
					}
					ele.goodsList.forEach((ele1,idx) => {
						len += ele1.buyNum;
						price += ele1.buyNum*ele1.goodsSku.price;
					})
				})
				self.amount = price;
				self.len = len;
			},
			pay() {
				if(!this.address){

						$.$toast("请选择收货地址");
							return

				}
				let carIds = uni.getStorageSync('orderCarIds') ? uni.getStorageSync('orderCarIds') : '';
				let addFormJson = [];//	[goodsDetail:[skuId:商品skuId,num:购买数量],carIds:购物车ID集合,couponId:优惠券ID,remark:备注,groupId:拼团购买方式>>-1单独购买>>0普通拼团>>其他为阶梯拼团ID]
				this.list.forEach((ele,index) => {
					let obj = {
						goodsDetail: [],
						carIds: carIds != '' && carIds[ele.shopId] ? carIds[ele.shopId] : '',
						couponId: ele.couponId ? ele.couponId : '',
						remark: ele.remark ? ele.remark : '',
						groupId: self.groupId,
						joinGroupId: self.joinGroupId,
						receiptInfo:this.invoiceData,
					}
					ele.goodsList.forEach((ele1,idx) => {
						let obj1 = {
							skuId: ele1.goodsSku.id,
							num: ele1.buyNum
						}
						obj.goodsDetail.push(obj1);
					})
					addFormJson.push(obj);
				})
				// addFormJson.push({
				// 		receiptInfo:this.invoiceData,
				// });

				console.log("addFormJson",addFormJson)
				console.log("postData1",postData)
				let postData = {
					addFormJson: JSON.stringify(addFormJson),
				}
				console.log("postData2",postData)
				this.address.addTime = '';
				postData =Object.assign(postData,this.address);



							console.log("postData3",postData)

			console.log("isflag",isflag)

				if(!isflag){return}
				isflag = false;
				$.ajax({
					url: API.addOrderApi,
					data: postData,
					method: 'POST',
					loading: true,
					loadingText: self.i18n['提交订单']+['…'],
					success(res) {
							isflag = true;
							console.log("success")
						let info = res.data;
						self.go('/pages/order/pay?orderNo='+info.payOrderNo+'&amount='+info.amount);
					},
					// complete() {
					// 	console.log("complete")
					// 	isflag = true;
					// },
					complete(e) {
						console.log("complete",e)
						isflag = true;
						if(e.message){
								// uni.showToast({
								// 	title: e.message,
								// 	icon: 'none',
								// 	duration: 5000
								// });
						}
					},
				})
			},
			getAddress() {
				$.ajax({
					url: API.getAddressApi,
					data: {},
					method: 'GET',
					success(res) {
						self.address = res.data ? res.data : '';
						self.getInfo();
					}
				})
			},
			setAddress(item) {
				this.address = item;
				self.getInfo();
			},

			getInfo() {
				let orderData = uni.getStorageSync('orderData') ? uni.getStorageSync('orderData') : '';
				let postData = {
					goodsParams: JSON.stringify(orderData),//[shopId,店铺ID,skuId:商品skuId,num:购买数量]
					groupId: self.groupId,//拼团购买方式>>-1单独购买>>0普通拼团>>其他为阶梯拼团ID
				}
				if(this.address != '') {
					self.address.addTime = '';
					postData = Object.assign(this.address,postData)
				}
				$.ajax({
					url: API.getOrderInfoApi,
					data: postData,
					method: 'POST',
					success(res) {
						self.list = res.data ? res.data : [];
						self.getPrice();
					}
				})
			},
	// 		getInfo() {
	// 			// let orderData = uni.getStorageSync('orderData') ? uni.getStorageSync('orderData') : '';
	// 			// 		console.log("	orderData",orderData)
	// 			// 					console.log("	this.orderData",	this.orderData)
	// 			// 				console.log("	orderData",JSON.stringify(this.orderData))
	// 			// let orderData =	this.orderData;


	// 			let postData = {
	// 				goodsParams: JSON.stringify(this.orderData),//[shopId,店铺ID,skuId:商品skuId,num:购买数量]
	// 				groupId: self.groupId,//拼团购买方式>>-1单独购买>>0普通拼团>>其他为阶梯拼团ID
	// 			}

	// 			if(this.address != '') {
	// 				self.address.addTime = '';
	// 				postData = Object.assign(this.address,postData)
	// 			}
	// 			$.ajax({
	// 				url: API.getOrderInfoApi,
	// 				data: postData,
	// 				method: 'POST',
	// 				success(res) {
	// 					self.list = res.data ? res.data : [];
	// 					self.getPrice();
	// 				}
	// 			})
	// 		},
			init() {
				this.getAddress();
			},
		},
		computed: {
			i18n() {
				return this.$t('order')
			},
		},
		created() {
		},
		onHide() {
			// uni.removeStorageSync('orderData');
		},
		mounted() {},
		destroyed() {},

		onPullDownRefresh() {
		},
		onReachBottom() {
		}
	}
</script>
